﻿using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace OfficeMiddlewareCore
{
    public class HttpServer
    {
        private HttpListener _listener = new HttpListener();
        private Thread _threadListener = null;

        public bool Start(int port)
        {
            try
            {
                if (_listener.IsListening)
                {
                    return true;
                }

                var ipList = Dns.GetHostAddresses(Dns.GetHostName());

                _listener.IgnoreWriteExceptions = true;
                _listener.Prefixes.Clear();
                var host = $"http://127.0.0.1:{port}/";
                _listener.Prefixes.Add(host);
                foreach (var ip in ipList)
                {
                    if (ip.AddressFamily.Equals(AddressFamily.InterNetwork))
                    {
                        host = $"http://{ip}:{port}/";
                        if (!_listener.Prefixes.Contains(host))
                        {
                            _listener.Prefixes.Add(host);
                        }
                    }

                }

                _listener.Start();
            }
            catch (Exception ex)
            {
                if (_listener.IsListening)
                {
                    _listener.Stop();
                }
                Debug.WriteLine(ex.Message);
                return false;
            }

            _threadListener = new Thread(() =>
            {
                while (_listener.IsListening)
                {
                    try
                    {
                        var request = _listener.GetContext();
                        ThreadPool.QueueUserWorkItem(ProcessRequest, request);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }

                }
            });

            _threadListener.Start();
            return true;
        }

        public void Stop()
        {
            if (_listener.IsListening)
            {
                _threadListener.Abort();
                _listener.Stop();
                _threadListener = null;
            }
        }

        private void ProcessRequest(object listenerContext)
        {
            var context = (HttpListenerContext)listenerContext;
            try
            {

            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
